/*
定时保存设备数据，如果设备数据发生变化
 */

'use strict';
const _ = require('lodash');
const moment = require("moment");
module.exports = {
    schedule: {
        cron: '0 0 * * * *', // 每小时
        //interval: '10s', // 任务的间隔时间, 这个定义的10秒执行一次
        type: 'worker' // 指定所有的 worker都需要执行
    },
    async task(ctx) {
        console.log('task', moment().format('YYYY-MM-DD HH:mm:ss'));
        ctx.app.eventBus.emit('MEETING_TASK',1);//会议室管理

        //  const cache = await ctx.app.dbs.find("PowerMeterCache", {});
        const curHourEndTs = moment().valueOf();
        const curHourStartTs = moment().add(-1, 'hours').valueOf();
        const lastHourStartTs = moment().add(-2, 'hours').valueOf();

        // console.log(ts, timeStr, moment(tsStart).format('YYYY-MM-DD HH:mm:ss'));
        const list = await ctx.app.dbs.find("IotDevice", {deviceType:{$regex: "智能电表"}});
        _.map(list, async meter => {
            const {deviceId, tenantCode} = meter;
            const curHour = await ctx.app.dbs.findLimit("IotReportData", {
                deviceId, tenantCode,
                time: {$gt: curHourStartTs, $lt: curHourEndTs}
            }, {time: -1}, 1);
            const lastHour = await ctx.app.dbs.findLimit("IotReportData", {
                deviceId, tenantCode,
                time: {$gt: lastHourStartTs, $lt: curHourStartTs}
            }, {time: -1}, 1);

            if (curHour.length > 0 && lastHour.length > 0) {
                const start = lastHour[0], end = curHour[0];
                const {status = 0} = start;
                const endStatus = end.status ? end.status : 0;
                const value = (endStatus - status).toFixed(2);
                delete meter._id;
                meter.value = value;
                meter.time = moment().valueOf();
                meter.timeStr = moment().format('YYYY-MM-DD HH') + ":00:00";
                meter.recordCode = deviceId + "-" + moment().format('YYYY-MM-DD HH:mm:ss');
                meter.TotalActiveEnergy1 = status;
                meter.TotalActiveEnergy2 = endStatus;
                meter.startData = start;
                meter.endData = end;
                const res1 = await ctx.app.dbs.insert("PowerMeterDay", meter);
            }

        });
        console.log("-------------------");
    }
};

